<template>
  <div class="asset-market-container">
    <n-card class="market-card">
      <template #header>
        <div class="card-header">
          <h1>素材市场</h1>
          <div class="search-box">
            <n-input v-model:value="searchQuery" placeholder="搜索素材..." clearable>
              <template #prefix>
                <n-icon><SearchOutline /></n-icon>
              </template>
            </n-input>
            <n-button type="primary" @click="search">搜索</n-button>
          </div>
        </div>
      </template>
      
      <div class="market-tabs">
        <n-tabs v-model:value="currentTab" type="line" animated>
          <n-tab-pane name="assets" tab="素材">
            <div class="market-filters">
              <n-space vertical>
                <div class="filter-section">
                  <n-space>
                    <n-select v-model:value="selectedCategory" :options="categoryOptions" placeholder="分类" style="width: 150px" />
                    <n-select v-model:value="selectedTime" :options="timeOptions" placeholder="时间" style="width: 150px" />
                    <n-select v-model:value="selectedSort" :options="sortOptions" placeholder="排序" style="width: 150px" />
                    <n-checkbox v-model:checked="freeOnly">仅显示免费</n-checkbox>
                    <n-button @click="resetFilters" quaternary>重置筛选</n-button>
                  </n-space>
                </div>
                
                <div v-if="activeTags.length > 0" class="active-tags">
                  <n-space>
                    <template v-for="tag in activeTags" :key="tag.key">
                      <n-tag closable @close="removeTag(tag.key)">{{ tag.label }}</n-tag>
                    </template>
                  </n-space>
                </div>
              </n-space>
            </div>
            
            <n-grid :cols="4" :x-gap="16" :y-gap="16">
              <n-grid-item v-for="asset in filteredAssets" :key="asset.id">
                <div class="asset-card" @click="viewAssetDetail(asset.id)">
                  <div class="asset-thumbnail">
                    <img :src="asset.thumbnail" :alt="asset.name">
                    <div class="asset-type">{{ asset.type }}</div>
                    <div v-if="asset.price === 0" class="asset-free">免费</div>
                  </div>
                  <div class="asset-info">
                    <div class="asset-name">{{ asset.name }}</div>
                    <div class="asset-meta">
                      <span class="asset-creator">{{ asset.creator }}</span>
                      <span class="asset-price">{{ asset.price > 0 ? `¥${asset.price}` : '免费' }}</span>
                    </div>
                    <div class="asset-stats">
                      <n-space>
                        <span class="stat"><n-icon><EyeOutline /></n-icon> {{ asset.views }}</span>
                        <span class="stat"><n-icon><DownloadOutline /></n-icon> {{ asset.downloads }}</span>
                        <span class="stat"><n-icon><StarOutline /></n-icon> {{ asset.rating }}</span>
                      </n-space>
                    </div>
                  </div>
                </div>
              </n-grid-item>
            </n-grid>
            
            <div class="pagination">
              <n-pagination 
                v-model:page="currentPage" 
                :page-count="totalPages" 
                :page-slot="5"
                show-quick-jumper
              />
            </div>
          </n-tab-pane>
          
          <n-tab-pane name="packs" tab="素材包">
            <div class="market-filters">
              <n-space>
                <n-select v-model:value="selectedPackCategory" :options="packCategoryOptions" placeholder="分类" style="width: 150px" />
                <n-select v-model:value="selectedPackSort" :options="packSortOptions" placeholder="排序" style="width: 150px" />
                <n-checkbox v-model:checked="freePacksOnly">仅显示免费</n-checkbox>
                <n-button @click="resetPackFilters" quaternary>重置筛选</n-button>
              </n-space>
            </div>
            
            <n-grid :cols="3" :x-gap="16" :y-gap="16">
              <n-grid-item v-for="pack in filteredPacks" :key="pack.id">
                <div class="pack-card" @click="viewPackDetail(pack.id)">
                  <div class="pack-thumbnail">
                    <img :src="pack.thumbnail" :alt="pack.name">
                    <div class="pack-count">{{ pack.assetCount }}个素材</div>
                    <div v-if="pack.price === 0" class="pack-free">免费</div>
                    <div v-if="pack.discount" class="pack-discount">-{{ pack.discount }}%</div>
                  </div>
                  <div class="pack-info">
                    <div class="pack-name">{{ pack.name }}</div>
                    <div class="pack-meta">
                      <span class="pack-creator">{{ pack.creator }}</span>
                      <span class="pack-price">
                        <template v-if="pack.originalPrice && pack.price !== pack.originalPrice">
                          <span class="original-price">¥{{ pack.originalPrice }}</span>
                          <span class="discount-price">¥{{ pack.price }}</span>
                        </template>
                        <template v-else>
                          {{ pack.price > 0 ? `¥${pack.price}` : '免费' }}
                        </template>
                      </span>
                    </div>
                    <div class="pack-stats">
                      <n-space>
                        <span class="stat"><n-icon><EyeOutline /></n-icon> {{ pack.views }}</span>
                        <span class="stat"><n-icon><DownloadOutline /></n-icon> {{ pack.downloads }}</span>
                        <span class="stat"><n-icon><StarOutline /></n-icon> {{ pack.rating }}</span>
                      </n-space>
                    </div>
                  </div>
                </div>
              </n-grid-item>
            </n-grid>
            
            <div class="pagination">
              <n-pagination 
                v-model:page="packCurrentPage" 
                :page-count="packTotalPages" 
                :page-slot="5"
                show-quick-jumper
              />
            </div>
          </n-tab-pane>
        </n-tabs>
      </div>
      
      <div class="market-actions">
        <n-space>
          <n-button @click="goToAssetPacks">
            <template #icon><n-icon><CubeOutline /></n-icon></template>
            素材包市场
          </n-button>
          <n-button @click="goToCreatorUpload" type="primary">
            <template #icon><n-icon><CloudUploadOutline /></n-icon></template>
            上传我的素材
          </n-button>
        </n-space>
      </div>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  NCard,
  NTabs,
  NTabPane,
  NInput,
  NButton,
  NSelect,
  NCheckbox,
  NPagination,
  NGrid,
  NGridItem,
  NSpace,
  NTag,
  NIcon
} from 'naive-ui'
import {
  SearchOutline,
  EyeOutline,
  StarOutline,
  DownloadOutline,
  CubeOutline,
  CloudUploadOutline
} from '@vicons/ionicons5'

const router = useRouter()

// 搜索与筛选
const searchQuery = ref('')
const currentTab = ref('assets')
const selectedCategory = ref(null)
const selectedTime = ref(null)
const selectedSort = ref('popular')
const freeOnly = ref(false)
const currentPage = ref(1)
const totalPages = ref(10)

// 素材包筛选
const selectedPackCategory = ref(null)
const selectedPackSort = ref('popular')
const freePacksOnly = ref(false)
const packCurrentPage = ref(1)
const packTotalPages = ref(5)

// 分类选项
const categoryOptions = [
  { label: '全部分类', value: null },
  { label: '角色', value: 'character' },
  { label: '场景', value: 'scene' },
  { label: '动作', value: 'action' },
  { label: '音效', value: 'sound' },
  { label: '特效', value: 'effect' },
  { label: '脚本', value: 'script' }
]

// 时间选项
const timeOptions = [
  { label: '全部时间', value: null },
  { label: '今日', value: 'today' },
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' },
  { label: '今年', value: 'year' }
]

// 排序选项
const sortOptions = [
  { label: '最受欢迎', value: 'popular' },
  { label: '最新', value: 'newest' },
  { label: '价格从低到高', value: 'price_asc' },
  { label: '价格从高到低', value: 'price_desc' },
  { label: '评分最高', value: 'rating' }
]

// 素材包分类选项
const packCategoryOptions = [
  { label: '全部分类', value: null },
  { label: '角色包', value: 'character' },
  { label: '场景包', value: 'scene' },
  { label: '音效包', value: 'sound' },
  { label: '综合包', value: 'mixed' }
]

// 素材包排序选项
const packSortOptions = [
  { label: '最受欢迎', value: 'popular' },
  { label: '最新', value: 'newest' },
  { label: '价格从低到高', value: 'price_asc' },
  { label: '价格从高到低', value: 'price_desc' },
  { label: '评分最高', value: 'rating' }
]

// 活跃标签
const activeTags = computed(() => {
  const tags = []
  
  if (searchQuery.value) {
    tags.push({ key: 'search', label: `搜索: ${searchQuery.value}` })
  }
  
  if (currentTab.value) {
    tags.push({ key: 'tab', label: getTabLabel(currentTab.value) })
  }
  
  if (selectedCategory.value) {
    const categoryOption = categoryOptions.find(opt => opt.value === selectedCategory.value)
    if (categoryOption) {
      tags.push({ key: 'category', label: `分类: ${categoryOption.label}` })
    }
  }
  
  if (selectedTime.value) {
    const timeOption = timeOptions.find(opt => opt.value === selectedTime.value)
    if (timeOption) {
      tags.push({ key: 'time', label: `时间: ${timeOption.label}` })
    }
  }
  
  if (freeOnly.value) {
    tags.push({ key: 'free', label: '仅免费素材' })
  }
  
  return tags
})

// 获取标签标签
function getTabLabel(tab: string): string {
  switch (tab) {
    case 'assets': return '素材'
    case 'packs': return '素材包'
    default: return tab
  }
}

// 移除标签
function removeTag(key: string): void {
  switch (key) {
    case 'search':
      searchQuery.value = ''
      break
    case 'tab':
      currentTab.value = 'assets'
      break
    case 'category':
      selectedCategory.value = null
      break
    case 'time':
      selectedTime.value = null
      break
    case 'free':
      freeOnly.value = false
      break
  }
}

// 重置筛选
function resetFilters(): void {
  selectedCategory.value = null
  selectedTime.value = null
  selectedSort.value = 'popular'
  freeOnly.value = false
  currentPage.value = 1
}

// 重置素材包筛选
function resetPackFilters(): void {
  selectedPackCategory.value = null
  selectedPackSort.value = 'popular'
  freePacksOnly.value = false
  packCurrentPage.value = 1
}

// 搜索
function search(): void {
  currentPage.value = 1
  // 实际项目中这里会调用API获取搜索结果
  console.log('Searching for:', searchQuery.value)
}

// 查看素材详情
function viewAssetDetail(id: string): void {
  router.push(`/asset-detail/${id}`)
}

// 查看素材包详情
function viewPackDetail(id: string): void {
  router.push(`/asset-pack/${id}`)
}

// 前往素材包市场
function goToAssetPacks(): void {
  router.push('/asset-packs')
}

// 前往创作者上传页面
function goToCreatorUpload(): void {
  router.push('/creator-upload')
}

// 模拟数据
const assets = ref([])
const packs = ref([])

// 过滤后的素材
const filteredAssets = computed(() => {
  // 实际项目中这里会根据筛选条件过滤数据
  return assets.value
})

// 过滤后的素材包
const filteredPacks = computed(() => {
  // 实际项目中这里会根据筛选条件过滤数据
  return packs.value
})

// 生成测试数据
function generateMockData() {
  // 生成素材
  assets.value = []
  for (let i = 1; i <= 20; i++) {
    const price = Math.random() > 0.3 ? Math.floor(Math.random() * 100) + 5 : 0
    
    // 随机标签
    const tags = []
    const tagCount = Math.floor(Math.random() * 5) + 1
    const allTags = ['角色', '场景', '动作', '特效', '音效', '脚本', '2D', '3D', '动画', '粒子']
    for (let j = 0; j < tagCount; j++) {
      const tag = allTags[Math.floor(Math.random() * allTags.length)]
      if (!tags.includes(tag)) {
        tags.push(tag)
      }
    }
    
    assets.value.push({
      id: `asset-${i}`,
      name: `素材 ${i}`,
      thumbnail: `https://picsum.photos/id/${i + 100}/300/200`,
      type: ['角色', '场景', '动作', '音效', '特效'][Math.floor(Math.random() * 5)],
      creator: `创作者${Math.floor(Math.random() * 10) + 1}`,
      price: price,
      views: Math.floor(Math.random() * 1000) + 100,
      downloads: Math.floor(Math.random() * 500) + 50,
      rating: (Math.random() * 2 + 3).toFixed(1),
      tags: tags,
      createdAt: getRandomDate()
    })
  }
  
  // 生成素材包
  packs.value = []
  for (let i = 1; i <= 6; i++) {
    const price = Math.floor(Math.random() * 300) + 50
    const discount = Math.random() > 0.5 ? Math.floor(Math.random() * 50) + 10 : 0
    const originalPrice = discount > 0 ? price + Math.floor(price * discount / 100) : price
    
    packs.value.push({
      id: `pack-${i}`,
      name: `素材包 ${i}`,
      thumbnail: `https://picsum.photos/id/${i + 200}/300/200`,
      creator: `创作者${Math.floor(Math.random() * 10) + 1}`,
      assetCount: Math.floor(Math.random() * 20) + 5,
      price: discount > 0 ? price : (Math.random() > 0.2 ? price : 0),
      originalPrice: discount > 0 ? originalPrice : null,
      discount: discount,
      views: Math.floor(Math.random() * 2000) + 500,
      downloads: Math.floor(Math.random() * 1000) + 100,
      rating: (Math.random() * 2 + 3).toFixed(1),
      category: ['角色包', '场景包', '音效包', '综合包'][Math.floor(Math.random() * 4)]
    })
  }
}

// 获取随机日期
function getRandomDate() {
  const now = new Date()
  const startDate = new Date()
  startDate.setMonth(now.getMonth() - 1)
  
  return new Date(startDate.getTime() + Math.random() * (now.getTime() - startDate.getTime()))
}

// 生命周期钩子
onMounted(() => {
  generateMockData()
})
</script>

<style lang="scss" scoped>
.asset-market-container {
  padding: 20px;
  
  .market-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
      }
      
      .search-box {
        display: flex;
        gap: 10px;
        width: 300px;
      }
    }
  }
  
  .market-filters {
    margin-bottom: 20px;
    padding: 16px;
    background-color: var(--card-color);
    border-radius: 4px;
    
    .filter-section {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 12px;
    }
  }
  
  .active-tags {
    margin-top: 12px;
  }
  
  .asset-card {
    border-radius: 8px;
    overflow: hidden;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    cursor: pointer;
    background-color: var(--card-color);
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    }
    
    .asset-thumbnail {
      position: relative;
      height: 150px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .asset-type {
        position: absolute;
        top: 8px;
        left: 8px;
        background-color: rgba(0, 0, 0, 0.6);
        color: white;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
      }
      
      .asset-free {
        position: absolute;
        top: 8px;
        right: 8px;
        background-color: var(--primary-color);
        color: white;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
      }
    }
    
    .asset-info {
      padding: 12px;
      
      .asset-name {
        font-weight: 500;
        margin-bottom: 4px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .asset-meta {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        font-size: 12px;
        
        .asset-creator {
          color: var(--text-color-2);
        }
        
        .asset-price {
          font-weight: 600;
          color: var(--primary-color);
        }
      }
      
      .asset-stats {
        display: flex;
        font-size: 12px;
        color: var(--text-color-3);
        
        .stat {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
  }
  
  .pack-card {
    border-radius: 8px;
    overflow: hidden;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    cursor: pointer;
    background-color: var(--card-color);
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    }
    
    .pack-thumbnail {
      position: relative;
      height: 180px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .pack-count {
        position: absolute;
        top: 8px;
        left: 8px;
        background-color: rgba(0, 0, 0, 0.6);
        color: white;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
      }
      
      .pack-free {
        position: absolute;
        top: 8px;
        right: 8px;
        background-color: var(--primary-color);
        color: white;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
      }
      
      .pack-discount {
        position: absolute;
        bottom: 8px;
        right: 8px;
        background-color: #f44336;
        color: white;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
      }
    }
    
    .pack-info {
      padding: 12px;
      
      .pack-name {
        font-weight: 500;
        margin-bottom: 4px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .pack-meta {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        font-size: 12px;
        
        .pack-creator {
          color: var(--text-color-2);
        }
        
        .pack-price {
          font-weight: 600;
          color: var(--primary-color);
          
          .original-price {
            text-decoration: line-through;
            color: var(--text-color-3);
            margin-right: 4px;
          }
          
          .discount-price {
            color: #f44336;
          }
        }
      }
      
      .pack-stats {
        display: flex;
        font-size: 12px;
        color: var(--text-color-3);
        
        .stat {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
  }
  
  .market-actions {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .asset-market-container {
    padding: 10px;
    
    .market-card {
      .card-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
        
        .search-box {
          width: 100%;
        }
      }
    }
    
    .market-filters {
      .filter-section {
        flex-direction: column;
        align-items: flex-start;
        
        .n-space {
          width: 100%;
          justify-content: space-between;
        }
      }
    }
  }
}
</style> 